<template>
  <div class="voicesWrapper">
    <draggable
      handle=".voiceCommandsHandler"
      animation="200"
      class="voices"
      v-model="voiceArr"
    >
      <transition-group>
        <div
          class="voiceItem"
          v-for="(item, index) in voiceArr"
          :key="item.key"
        >
          <div class="voiceCommandsHandler"></div>
          <el-input class="input" v-model="item.value" />
          <img
            class="add"
            src="@/assets/img/manage/add.svg"
            alt=""
            @click="addVoice(index + 1)"
          />
          <img
            v-if="voiceArr.length > 1"
            src="@/assets/img/manage/delete.svg"
            alt=""
            class="delete"
            @click="deleteVoice(item.key)"
          />
        </div>
      </transition-group>
    </draggable>
  </div>
</template>

<script setup lang="ts">
import { nextTick, ref, watch } from "vue";
import { VueDraggableNext as draggable } from "vue-draggable-next";
import { randomString } from "../utils";

const props = defineProps(["data"]);
const emit = defineEmits(["update:data"]);
const voiceArr = ref(props.data);

const addVoice = (index) => {
  const data = voiceArr.value;
  data.splice(index, 0, {
    key: randomString(),
    value: "",
  });
};

const deleteVoice = (index) => {
  const data = voiceArr.value;
  const i = data.findIndex((v) => v.key === index);
  data.splice(i, 1);
};

watch(
  () => props.data,
  (newVale) => {
    voiceArr.value = newVale;
    if (newVale.length === 0) {
      nextTick(() => {
        addVoice(0);
      });
    }
  },
  {
    immediate: true,
  }
);

defineExpose({
  voiceArr,
});
</script>

<style scoped lang="scss">
.voicesWrapper {
  .voices {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }
  .voiceItem {
    display: flex;
    justify-content: flex-start;
    gap: 10px;
    .voiceCommandsHandler {
      width: 10px;
      height: 32px;
      background-color: #eee;
      cursor: move;
    }
    .input {
      width: 500px;
    }
    & .add,
    .delete {
      position: relative;
      top: 3px;
      width: 25px;
      height: 25px;
      &:hover {
        cursor: pointer;
      }
    }
  }
}
</style>
